use config::Config;
use nickel::{HttpRouter, Nickel, Options};
use server::ServerUtils;

pub mod config;
pub mod data;
pub mod error;
pub mod server;
pub mod utils;

pub static INDEX_KEY: &str = "$index";
pub static MAGIC_QUERY_KEY: &str = "$query";
pub static DEFAULT_FILE: &str = "server.json";

#[macro_use]
extern crate nickel;

#[macro_use]
extern crate serde;

trait ForceUnwrap<T: std::fmt::Debug> {
    fn force_unwrap(self) -> T;
}

impl<T: std::fmt::Debug> ForceUnwrap<T> for Option<T> {
    fn force_unwrap(self) -> T {
        match self {
            Some(t) => t,
            None => {
                println!("Unexpected none value at {:?}", self);
                std::process::exit(0);
            }
        }
    }
}

impl<T: std::fmt::Debug, E: std::fmt::Debug> ForceUnwrap<T> for Result<T, E> {
    fn force_unwrap(self) -> T {
        match self {
            Ok(t) => t,
            Err(e) => {
                println!("Unexpected error at {:?}", e);
                std::process::exit(0);
            }
        }
    }
}

/// start main run function
pub fn run(config: Config) {
    let mut server = Nickel::new();
    server.options = Options::default().output_on_listen(false);

    config.print_logo();
    config.print_table();
    let html = config.generate_index_html();
    server.get("/", middleware!(format!("{}", html)));

    server::curd_implement(&config, &mut server);
    server.listen(config.server_url()).unwrap();
}
